package com.tianji.learning.redis;

import cn.hutool.json.JSON;
import com.google.gson.Gson;
import com.tianji.common.domain.R;
import com.tianji.common.utils.JsonUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.learning.domain.po.LearningRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.time.Duration;

@Component
@Slf4j
public class RedisCacheTemplate {
    @Autowired
    private StringRedisTemplate redisTemplate;
    private final String Record_Key_Template ="record_key_{}";

    /**
     *  从redis中读取对应key是否存在
     * @param lessonId
     * @param sectionId
     * @return
     */
    public LearningRecord redisCacheQueryRecord(Long lessonId,Long sectionId){
        try {
            String key = StringUtils.format(Record_Key_Template, lessonId);
            Object cacheData = redisTemplate.opsForHash().get(key, sectionId.toString());
            if(cacheData == null){
                return null;
            }
            return JsonUtils.toBean(cacheData.toString(),LearningRecord.class);
        }catch (Exception e){
            log.error("查询缓存失败",e);
            return null;
        }

    }

    public void redisCacheWriteRecord(LearningRecord record) {
        log.debug("更新学习记录的缓存数据:{}",record.getId());
        try {
            //1.数据转换
            RecordCacheData recordCacheData = new RecordCacheData(record);
            Gson gson = new Gson();
            String json = gson.toJson(recordCacheData);
//            String json = JsonUtils.toJsonStr(recordCacheData);
            //2.写入redis
            String key = StringUtils.format(Record_Key_Template, record.getLessonId());
            redisTemplate.opsForHash().put(key,record.getSectionId().toString(),json);
            //3.添加缓存过期时间
//            redisTemplate.expire(key, Duration.ofMinutes(1));
        }catch (Exception e){
            log.error("更新学习记录缓存异常",e);
        }
    }

    public void cleanCache(Long lessonId, Long sectionId) {
        log.debug("清理学习记录的缓存");
        String key = StringUtils.format(Record_Key_Template, lessonId);
        redisTemplate.opsForHash().delete(key,sectionId.toString());

    }

    private static class RecordCacheData implements Serializable {
        private Long id;
        private Integer moment;
        private Boolean finished;

        public RecordCacheData(LearningRecord record) {
            this.id=record.getId();
            this.moment=record.getMoment();
            this.finished=record.getFinished();
        }
    }
}
